package com.mz.mattress.admin.interceptor;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.mz.mattress.admin.common.Holder;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一拦截异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ExceptionHandler(WxPayException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<?> handleWxPayException(WxPayException e) {
        log(e);
        return Result.fail(e.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Result<?> handleServiceException(ServiceException e) {
        log(e);
        return Result.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handleValidException(MethodArgumentNotValidException e) {
        log(e);
        return handleValidationException(e.getBindingResult());
    }

    @ExceptionHandler(value = BindException.class)
    public Result<?> handleValidException(BindException e) {
        log(e);
        return handleValidationException(e.getBindingResult());
    }

    private Result<?> handleValidationException(BindingResult bindingResult) {
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
//                message = fieldError.getField() + fieldError.getDefaultMessage();
                return Result.fail(fieldError.getDefaultMessage());
            }
        }
        return Result.fail();
    }

    private void log(Exception e) {
        log.error("global_error", e);
    }
}
